<template>
  <div>
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>容器环境管理</el-breadcrumb-item>
      <el-breadcrumb-item>Web Terminal</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="box-card">
      <div id="terminal" class="xterm"></div>
    </el-card>
  </div>
</template>

<script>
  import { Terminal } from 'xterm'
  import { FitAddon } from 'xterm-addon-fit/out/FitAddon'
  import { AttachAddon } from 'xterm-addon-attach/out/AttachAddon'

  export default {
    name: 'AttachContainer',
    data() {
      return {
        // containerId: '738d20484fe3',
        // nodeIp: '172.18.2.223'
      }
    },
    mounted() {
       const term = new Terminal(
        {
          cols: 500,
          cursorBlink: true,
          cursorStyle: 'block'

        }
      )
      const fitAddon = new FitAddon()
      const socket = new WebSocket(`ws://${this.$route.query.containerNode}:2375/containers/${this.$route.query.containeID}/attach/ws?logs=1&stream=1&stdin=1&stdout=1&stderr=1 HTTP/1.1`)
      // const socket = new WebSocket(`ws://${this.$route.query.containerNode}:2375/containers/${this.$route.query.containeID}/attach/ws?AttachStdin=1&stdin=1&AttachStdout=1&AttachStderr=1&Cmd=date HTTP/1.1`)
      const attachAddon = new AttachAddon(socket)
      this.$nextTick(() => {
        // 当三方类都加载完以后开始执行下边的query
        document.querySelector('.xterm-viewport').style.display = 'none'
        document.querySelector('.xterm-char-measure-element').style.display = 'none'
        document.querySelector('.xterm-helper-textarea').style = 'display:block;border:#ffff solid 0px;border-width:1 1 1 1;color:#ffff;outline:none;resize:none'
      })
      term.loadAddon(attachAddon)
      term.loadAddon(fitAddon)
      term.open(document.getElementById('terminal'))
      fitAddon.fit()
      term.focus()
      socket.onopen = () => { socket.send('\n') } // 当连接建立时向终端发送一个换行符，不这么做的话最初终端是没有内容的，输入换行符可让终端显示当前用户的工作路径
      //
      // window.onresize = function() { // 窗口尺寸变化时，终端尺寸自适应
      //   fitAddon.fit()
      // }

      this.term = term
      this.socket = socket
    },
    beforeDestroy() {
      this.socket.close()
      this.term.dispose()
    }
  }
</script>

<style scoped>
  #terminal{
   height: 800px;
  }
  .box-card {
    width: 100%;
    margin-top: 10px;
    height: 100%;
  }
</style>
